package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan.adjust;

import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.citrus.cr.common.annotation.EpochTransactional;
import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.CalculatePercentage;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanLineWriteService;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.BatchUpdateLineStatusRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanAdjustDetailRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanAdjustDetailBatchQueryRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.citrus.cr.sales.plan.functions.salesplan.SalesPlanLineAbility;
import com.alibaba.citrus.cr.sales.plan.functions.salesplan.adjust.SalesPlanAdjustDetailAbility;
import com.alibaba.citrus.cr.sales.plan.functions.salesplan.adjust.SalesPlanAdjustDetailEntity;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanLineStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.model.features.SalesPlanAdjustDetailFeatures;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanAdjustDetailRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanLineRepository;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanAdjustDetailSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanLineSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.adjust.SalesPlanAdjustDetailWriteService;
import com.alibaba.citrus.cr.sales.plan.api.statistics.SalesPlanStatService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.EditSalesPlanAdjustDetailRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanLineRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QueryPlanAdjustDetailRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.UpdateAdjustCountRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.crplatformenhance.domain.customersalescope.model.CustomerSaleScope;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-10-25 16:18
 */
@Service
public class SalesPlanAdjustDetailWriteServiceImpl implements SalesPlanAdjustDetailWriteService {

    private final static Logger log = LoggerFactory.getLogger(SalesPlanAdjustDetailWriteServiceImpl.class);

    private static final String DEFAULT_FROM_SYS = "APP_OTS";

    private static final String DEFAULT_BUSINESS_TYPE = "11";

    private static final String DEFAULT_SC_ITEM_UNIT = "PC";

    @Resource
    private SalesPlanAdjustDetailAbility salesPlanAdjustDetailAbility;

    @Resource
    private SalesPlanAdjustDetailRepository salesPlanAdjustDetailRepository;

    @Resource
    private SalesPlanQueryService salesPlanQueryService;

    @Resource
    private SalesPlanLineWriteService salesPlanLineWriteService;

    @Resource
    private SalesPlanLineAbility salesPlanLineAbility;

    @Resource
    private SalesPlanLineRepository salesPlanLineRepository;

    @Resource
    private SalesPlanStatService salesPlanStatService;

    @Resource
    private SalesPlanCommonService salesPlanCommonService;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

    /**
     * 计划明细page_size
     */
    private static final Integer SALES_PLAN_LIN_PAGE_SIZE = 500;

    @Override
    @EpochTransactional(appCode = "bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @FacadeInvoker
    public Result<String> batchCreateSalesPlanAdjustDetail(List<SalesPlanAdjustDetailSDO> salesPlanAdjustDetailSDOList) {
        if (CollectionUtils.isEmpty(salesPlanAdjustDetailSDOList)) {
            throw new FacadeException("OTS-02-002-02-15-013");
        }

        SalesPlanSDO planSDO = salesPlanCommonService.checkSalesPlan(salesPlanAdjustDetailSDOList.stream().findFirst().get().getPlanId());

        //SalesPlanSDO adjustPlanSDO = salesPlanCommonService.checkSalesPlan(salesPlanAdjustDetailSDOList.stream().findFirst().get().getAdjustId().toString());

        //adjustId+客户收收获地址编码+货品编码查询重复数据，重复则更新，否则新增
        Set<Long> adjustIdSet = salesPlanAdjustDetailSDOList.stream().map(SalesPlanAdjustDetailSDO::getAdjustId).collect(Collectors.toSet());
        Set<String> customerAddresSet = salesPlanAdjustDetailSDOList.stream().map(SalesPlanAdjustDetailSDO::getCustomerAddress).collect(Collectors.toSet());
        Set<String> scItemIdSet = salesPlanAdjustDetailSDOList.stream().map(SalesPlanAdjustDetailSDO::getScItemId).collect(Collectors.toSet());
        Set<String> customerAddressIdSet = salesPlanAdjustDetailSDOList.stream().map(SalesPlanAdjustDetailSDO::getCustomerAddressId).filter(StringUtils::isNotBlank).collect(Collectors.toSet());

        SalesPlanAdjustDetailBatchQueryRequest salesPlanAdjustDetailBatchQueryRequest = new SalesPlanAdjustDetailBatchQueryRequest();
        salesPlanAdjustDetailBatchQueryRequest.setAdjustIds(Lists.newArrayList(adjustIdSet));
        salesPlanAdjustDetailBatchQueryRequest.setCustomerAddress(Lists.newArrayList(customerAddresSet));
        if (CollectionUtils.isNotEmpty(customerAddressIdSet)) {
            salesPlanAdjustDetailBatchQueryRequest.setCustomerAddressId(Lists.newArrayList(customerAddressIdSet));
        }
        salesPlanAdjustDetailBatchQueryRequest.setScItemIds(Lists.newArrayList(scItemIdSet));
        List<SalesPlanAdjustDetailSDO> salesPlanAdjustDetailSDOS = salesPlanAdjustDetailRepository.batchQueryDetail(salesPlanAdjustDetailBatchQueryRequest);
        if (salesPlanAdjustDetailSDOS.size() > 0) {
            throw new FacadeException("OTS-02-005-00-15-009");
        }

        //添加月度计划明细
        List<SalesPlanLineSDO> salesPlanLineSDOList = salesPlanAdjustDetailSDOList.stream().map(salesPlanAdjustDetailSDO -> {
            SalesPlanLineSDO salesPlanLineSDO = SalesPlanLineSDO.builder().build();
            BeanUtils.copyProperties(salesPlanAdjustDetailSDO, salesPlanLineSDO);
            salesPlanLineSDO.setStatus(SalesPlanLineStatusEnum.ADJUST_ADD.getStatus());
            return salesPlanLineSDO;
        }).collect(Collectors.toList());

        //补上计划明细的客户组
        Set<String> customerCodeSet = salesPlanLineSDOList.stream().map(SalesPlanLineSDO::getCustomerCode).collect(Collectors.toSet());
        Map<String, CustomerSaleScope> customerSaleScopeMap = salesPlanOutCommonService.getCustomerSaleScopeMap(customerCodeSet);
        for (SalesPlanLineSDO planLineSDO : salesPlanLineSDOList) {
            CustomerSaleScope customerSaleScope = customerSaleScopeMap.get(planLineSDO.getCustomerCode());
            if (customerSaleScope!=null) {
                planLineSDO.setParam2(customerSaleScope.getCustomerGroup());
            }
        }

        //获取合同量
        salesPlanCommonService.fillContractInfoAndModifySalesPlanDetails(salesPlanLineSDOList);

        //补充业中计划明细字段
        enichBcPlanField(salesPlanLineSDOList,planSDO);

        String successCount = salesPlanLineAbility.batchCreateSalesPlanLine(salesPlanLineSDOList);
        if (Integer.parseInt(successCount) > 0) {
            //新增调整明细
            SalesPlanAdjustDetailSDO firstPlanAdjustDetailSDO = salesPlanAdjustDetailSDOList.stream().findFirst().get();
            PageQueryPlanLineRequest queryPlanLineRequest = new PageQueryPlanLineRequest();
            queryPlanLineRequest.setPlanId(firstPlanAdjustDetailSDO.getPlanId());
            queryPlanLineRequest.setStatus(SalesPlanLineStatusEnum.ADJUST_ADD.getStatus());
            queryPlanLineRequest.setCustomerAddresss(Lists.newArrayList(customerAddresSet));
            if (CollectionUtils.isNotEmpty(customerAddressIdSet)) {
                queryPlanLineRequest.setCustomerAddressIdList(Lists.newArrayList(customerAddressIdSet));
            }
            queryPlanLineRequest.setScItemIds(Lists.newArrayList(scItemIdSet));
            //获取总数
            PageResult<List<SalesPlanLineSDO>> listPageResult = salesPlanLineRepository.pageQuerySalesPlanLineAdjustAddList(queryPlanLineRequest);
            int totalPage = (listPageResult.getTotal() + SALES_PLAN_LIN_PAGE_SIZE - 1) / SALES_PLAN_LIN_PAGE_SIZE;
            //调整明细数据
            List<SalesPlanAdjustDetailSDO> sdoList = new ArrayList<>();
            for (int i = 1; i <= totalPage; i++) {
                queryPlanLineRequest.setSize(SALES_PLAN_LIN_PAGE_SIZE);
                queryPlanLineRequest.setPage(i);
                PageResult<List<SalesPlanLineSDO>> listPageResult2 = salesPlanLineRepository.pageQuerySalesPlanLineAdjustAddList(queryPlanLineRequest);
                if (CollectionUtils.isEmpty(listPageResult2.getContent())) {
                    break;
                }
                listPageResult2.getContent().forEach(salesPlanLineSDO -> {
                    SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = SalesPlanAdjustDetailSDO.builder().build();
                    BeanUtils.copyProperties(salesPlanLineSDO, salesPlanAdjustDetailSDO);
                    salesPlanAdjustDetailSDO.setAdjustId(firstPlanAdjustDetailSDO.getAdjustId());
                    salesPlanAdjustDetailSDO.setPlanId(firstPlanAdjustDetailSDO.getPlanId());
                    salesPlanAdjustDetailSDO.setPlanDetailId(salesPlanLineSDO.getId());
                    salesPlanAdjustDetailSDO.setEstimatedDiscountRate(salesPlanLineSDO.getEstimatedDiscountRate().longValue());
                    salesPlanAdjustDetailSDO.setStatus(SalesPlanLineStatusEnum.FINISH.getStatus());
                    //调整新数据标识
                    SalesPlanAdjustDetailFeatures salesPlanAdjustDetailFeatures = new SalesPlanAdjustDetailFeatures();
                    salesPlanAdjustDetailFeatures.setIsHistory(false);
                    salesPlanAdjustDetailSDO.setFeatures(JSONObject.toJSONString(salesPlanAdjustDetailFeatures));
                    sdoList.add(salesPlanAdjustDetailSDO);
                });
            }

            salesPlanAdjustDetailAbility.batchCreateSalesPlanAdjustDetail(sdoList);
        }
        return Result.success(successCount);
    }


    /**
     * 补充业中计划明细字段
     * @param createPlanLineSdoList
     * @param planSDO
     */
    private void enichBcPlanField(List<SalesPlanLineSDO> createPlanLineSdoList,SalesPlanSDO planSDO) {
        Set<String> scItemIdSet = createPlanLineSdoList.stream().filter(x->StringUtils.isBlank(x.getScItemCode())).map(SalesPlanLineSDO::getScItemId).collect(Collectors.toSet());
        Set<String> orgSalesOrganizationIdSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getOrgSalesOrganizationCode).collect(Collectors.toSet());

        Map<String, ScItemSDO> queryScItemMap = salesPlanOutCommonService.getScItemMapByIds(scItemIdSet, false);
        Map<String, OrganizationSDO> queryOrganizationMap = salesPlanOutCommonService.getOrganizationMapByIds(orgSalesOrganizationIdSet, false);

        String warehouseCode = "-1";
        Map<String, com.epoch.app.crplatformenhance.sdo.OrganizationSDO> orgBusinessUnitMap = salesPlanOutCommonService.getOrganizationMapByOutCode(Sets.newHashSet(planSDO.getOrgBusinessUnitOrgcode()));
        if (MapUtils.isNotEmpty(orgBusinessUnitMap)) {
            com.epoch.app.crplatformenhance.sdo.OrganizationSDO orgBusinessUnit = orgBusinessUnitMap.get(planSDO.getOrgBusinessUnitOrgcode());
            List<WarehouseInfo> sharedWarehouseList = salesPlanOutCommonService.getSharedWarehouseListBySaleOrgId(orgBusinessUnit.getId());
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(sharedWarehouseList)) {
                warehouseCode = sharedWarehouseList.get(0).getCode();
            }
        }

        Long maxPlanLineNo = salesPlanLineRepository.queryMaxPlanLineNo(planSDO.getId());

        for (SalesPlanLineSDO sdo : createPlanLineSdoList) {
            maxPlanLineNo++;
            sdo.setPlanNo(planSDO.getPlanNo());
            sdo.setPlanDetailNo(String.valueOf(maxPlanLineNo));
            sdo.setOrgEnterpriseGroupCode(planSDO.getOrgEnterpriseGroupCode());
            sdo.setOrgRegionCode(planSDO.getOrgRegionCode());
            sdo.setOrgProvinceCode(planSDO.getOrgProvinceCode());
            sdo.setBizUnitCode(planSDO.getOrgBusinessUnitOrgcode());

            sdo.setWarehouseCode(warehouseCode);

            if (StringUtils.isNotBlank(sdo.getOrgSalesOrganizationCode()) && MapUtils.isNotEmpty(queryOrganizationMap)) {
                OrganizationSDO organizationSDO = queryOrganizationMap.get(sdo.getOrgSalesOrganizationCode());
                sdo.setOrgSalesOrganizationOrgcode(organizationSDO!=null?organizationSDO.getCode():null);
            }

            if (StringUtils.isBlank(sdo.getScItemCode()) && MapUtils.isNotEmpty(queryScItemMap)) {
                ScItemSDO scItemSDO = queryScItemMap.get(sdo.getScItemId());
                sdo.setScItemCode(scItemSDO!=null?scItemSDO.getOuterId():null);
                sdo.setScItemBrandId(scItemSDO!=null?scItemSDO.getBrandId():null);
            }
            sdo.setScItemGroup(StringUtils.isNoneBlank(sdo.getScItemGroup())?sdo.getScItemGroup():DEFAULT_BUSINESS_TYPE);
            sdo.setBasicUnit(StringUtils.isNoneBlank(sdo.getBasicUnit())?sdo.getBasicUnit():DEFAULT_SC_ITEM_UNIT);

            sdo.setBusinessType(DEFAULT_BUSINESS_TYPE);
            sdo.setFromSys(DEFAULT_FROM_SYS);

            sdo.setPlanTime(DateUtils.toDateStr(Long.parseLong(planSDO.getPlanTime()),DateUtils.PATTEN_YM_PLAIN));

            //常规销售价
            long costInsuranceFreight = Objects.nonNull(sdo.getCostInsuranceFreight()) ? sdo.getCostInsuranceFreight() : 0;
            //估计折扣率,估计折扣价
            BigDecimal estimatedDiscountRate = planSDO.getEstimateDiscount().multiply(new BigDecimal(100));
            sdo.setEstimatedDiscountRate(estimatedDiscountRate.intValue());
            BigDecimal discount = BigDecimal.ONE.subtract(planSDO.getEstimateDiscount().multiply(new BigDecimal("0.01").setScale(2, RoundingMode.HALF_UP)));
            BigDecimal estimatedDiscountPrice = new BigDecimal(costInsuranceFreight).multiply(discount).setScale(0, RoundingMode.HALF_UP);
            sdo.setEstimatedDiscountPrice(estimatedDiscountPrice.longValue());
        }
    }

    @Override
    @EpochTransactional(appCode = "bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @FacadeInvoker
    public Result<SalesPlanAdjustDetailSDO> editSalesPlanAdjustDetail(EditSalesPlanAdjustDetailRequest editSalesPlanAdjustDetailRequest) {
        QueryPlanAdjustDetailRequest queryPlanAdjustDetailRequest = new QueryPlanAdjustDetailRequest();
        queryPlanAdjustDetailRequest.setId(editSalesPlanAdjustDetailRequest.getId());
        SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = salesPlanAdjustDetailRepository.querySalesPlanAdjustDetailList(queryPlanAdjustDetailRequest);
        if (Objects.isNull(salesPlanAdjustDetailSDO)) {
            throw new FacadeException("OTS-02-005-00-15-003");
        }
        SalesPlanAdjustDetailSDO editSdo = editSalesPlanRequestConverter(salesPlanAdjustDetailSDO, editSalesPlanAdjustDetailRequest);
        SalesPlanAdjustDetailEntity salesPlanLineEntity = SalesPlanAdjustDetailEntity.of(editSdo);
        Integer count = salesPlanLineEntity.doEdit();
        if (count > 0) {
            if (editSdo.getPlanDetailId() != null) {
                //更新月度计划明细
                UpdateAdjustCountRequest updateAdjustCountRequest = new UpdateAdjustCountRequest();
                updateAdjustCountRequest.setId(editSdo.getPlanDetailId());
                updateAdjustCountRequest.setAdjustCount(editSdo.getAdjustCount());
                updateAdjustCountRequest.setAdjustMoney(editSdo.getAdjustMoney());
                updateAdjustCountRequest.setBeforeAdjustMoney(editSdo.getBeforeAdjustMoney());
                updateAdjustCountRequest.setMonthFirstAdjustCount(editSdo.getMonthFirstAdjustCount());
                updateAdjustCountRequest.setMonthMiddleAdjustCount(editSdo.getMonthMiddleAdjustCount());
                updateAdjustCountRequest.setMonthLastAdjustCount(editSdo.getMonthLastAdjustCount());
//                updateAdjustCountRequest.setMonthFirstAdjustReturnCount(editSdo.getMonthFirstAdjustReturnCount());
//                updateAdjustCountRequest.setMonthMiddleAdjustReturnCount(editSdo.getMonthMiddleAdjustReturnCount());
//                updateAdjustCountRequest.setMonthLastAdjustReturnCount(editSdo.getMonthLastAdjustReturnCount());
                salesPlanLineWriteService.updateAdjustCount(updateAdjustCountRequest);
            }
        }
        return Result.success(salesPlanAdjustDetailRepository.querySalesPlanAdjustDetailList(queryPlanAdjustDetailRequest));
    }

    @Override
    @EpochTransactional(appCode = "bc_ots", dataSourceCode = "cr_ots", dataSourceType = "app")
    @FacadeInvoker
    public Result<Integer> batchUpdateAdjustDetailStatus(BatchUpdateLineStatusRequest batchUpdateLineStatusRequst) {
        List<SalesPlanAdjustDetailSDO> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(batchUpdateLineStatusRequst.getSalesPlanLineSDOList())) {
            SalesPlanAdjustDetailBatchQueryRequest queryRequest = new SalesPlanAdjustDetailBatchQueryRequest();
            List<Long> ids = batchUpdateLineStatusRequst.getSalesPlanLineSDOList().stream().map(x -> x.getId()).collect(Collectors.toList());
            queryRequest.setIds(ids);
            result = salesPlanAdjustDetailRepository.batchQueryDetail(queryRequest);
        } else {
            //支持按条件查询批量删除
            if (StringUtils.isBlank(batchUpdateLineStatusRequst.getPlanId())) {
                throw new FacadeException("OTS-02-004-01-15-001");
            }
            if (StringUtils.isBlank(batchUpdateLineStatusRequst.getAdjustId())) {
                throw new FacadeException("OTS-02-004-01-15-018");
            }
            int limit = 1000;
            PageQueryPlanAdjustDetailRequest queryRequest = pageQueryPlanAdjustDetailRequestConverter(batchUpdateLineStatusRequst);
            queryRequest.setStart(0);
            queryRequest.setLimit(limit);
            PageResult<List<SalesPlanAdjustDetailSDO>> response = salesPlanAdjustDetailRepository.pageQuerySalesPlanAdjustDetailList(queryRequest);
            if (response != null && CollectionUtils.isNotEmpty(response.getContent())) {
                result.addAll(response.getContent());
            }
            log.info("SalesPlanAdjustDetailWriteServiceImpl_batchUpdateLineStatus_queryESSalesPlanLine_getTotal={}", response.getTotal());

            int totalPage = response.getTotal() / limit;
            if (response.getTotal() % limit > 0) {
                totalPage++;
            }
            for (int pageNo = 1; pageNo < totalPage; pageNo++) {
                queryRequest.setStart(pageNo * limit);
                queryRequest.setLimit(limit);
                PageResult<List<SalesPlanAdjustDetailSDO>> response2 = salesPlanAdjustDetailRepository.pageQuerySalesPlanAdjustDetailList(queryRequest);
                if (response2 != null && CollectionUtils.isNotEmpty(response2.getContent())) {
                    result.addAll(response2.getContent());
                }
            }
        }
        log.info("SalesPlanAdjustDetailWriteServiceImpl_batchUpdateLineStatus_getSalesPlanLine_size={}", result.size());
        if (result.size() <= 0) {
            throw new FacadeException("OTS-02-005-00-15-003");
        }
        //判断是否存在原始数据,原始数据不允许删除,新数据允许删除
        for (SalesPlanAdjustDetailSDO x : result) {
            if (Objects.isNull(x.getSalesPlanAdjustDetailFeatures()) || x.getSalesPlanAdjustDetailFeatures().getIsHistory()) {
                throw new FacadeException("OTS-02-005-00-16-003");
            }
        }

        Integer integer = 0;
        if (result.size() > 500) {
            int size = 500;
            int count = result.size() / size;
            if (result.size() % size > 0) {
                count++;
            }
            for (int i = 0; i < count; i++) {
                int start = i * size;
                int end = i + 1 == count ? result.size() : start + size;
                List<SalesPlanAdjustDetailSDO> list = result.subList(start, end);
                //删除调整明细新数据
                Integer line = salesPlanAdjustDetailAbility.batchUpdateAdjustDetailStatus(list);
                //删除新增计划新数据
                List<SalesPlanLineSDO> list2 = new ArrayList<>();
                list.stream().forEach(x -> {
                    SalesPlanLineSDO salesPlanLineSDO = new SalesPlanLineSDO();
                    salesPlanLineSDO.setId(x.getPlanDetailId());
                    list2.add(salesPlanLineSDO);
                });
                salesPlanLineRepository.batchUpdateLineStatus(list2);

                integer = integer + line;
            }
        } else {
            //删除调整明细新数据
            integer = salesPlanAdjustDetailAbility.batchUpdateAdjustDetailStatus(result);
            //删除新增计划新数据
            List<SalesPlanLineSDO> salesPlanLineSDOList = new ArrayList<>();
            result.stream().forEach(x -> {
                SalesPlanLineSDO salesPlanLineSDO = new SalesPlanLineSDO();
                salesPlanLineSDO.setId(x.getPlanDetailId());
                salesPlanLineSDOList.add(salesPlanLineSDO);
            });
            salesPlanLineRepository.batchUpdateLineStatus(salesPlanLineSDOList);
        }

        //触发删除汇总动作
        SalesPlanAdjustDetailSDO detailSDO = result.stream().findFirst().get();
        salesPlanStatService.planCollect(detailSDO.getPlanId());
        return Result.success(integer);
    }

    private PageQueryPlanAdjustDetailRequest pageQueryPlanAdjustDetailRequestConverter(BatchUpdateLineStatusRequest batchUpdateLineStatusRequst) {
        PageQueryPlanAdjustDetailRequest queryRequest = new PageQueryPlanAdjustDetailRequest();
        queryRequest.setPlanId(batchUpdateLineStatusRequst.getPlanId());
        queryRequest.setAdjustId(batchUpdateLineStatusRequst.getAdjustId());

        //增加货品编码查询
        List<String> scItemIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(batchUpdateLineStatusRequst.getScItemIdList())) {
            scItemIdList.addAll(batchUpdateLineStatusRequst.getScItemIdList());
        }
        if (StringUtils.isNotBlank(batchUpdateLineStatusRequst.getScItemCode())) {
            Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(Sets.newHashSet(batchUpdateLineStatusRequst.getScItemCode()));
            if (scItemMap != null) {
                scItemIdList.addAll(scItemMap.values().stream().map(x -> x.getScItemId()).collect(Collectors.toList()));
            } else {
                scItemIdList.add("-1");
            }
        }
        if (CollectionUtils.isNotEmpty(scItemIdList)) {
            queryRequest.setScItemIds(scItemIdList);
        }

        queryRequest.setScItemLeafCategoryIdList(batchUpdateLineStatusRequst.getScItemLeafCategoryIdList());
        queryRequest.setCustomerCode(batchUpdateLineStatusRequst.getCustomerCode());
        queryRequest.setCustomerAddress(batchUpdateLineStatusRequst.getCustomerAddress());
        queryRequest.setManageEmployeeId(batchUpdateLineStatusRequst.getManageEmployeeId());
        queryRequest.setContractDifferenceMoneyStamp(batchUpdateLineStatusRequst.getContractDifferenceMoneyStamp());
        SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(batchUpdateLineStatusRequst.getBizType());
        if (byOrganizationType == null) {
            QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
            querySalesPlanRequest.setId(batchUpdateLineStatusRequst.getPlanId());
            Result<SalesPlanSDO> result = salesPlanQueryService.getSalesPlan(querySalesPlanRequest);
            if (!result.isSuccess() || null == result.getResult()) {
                throw new FacadeException("OTS-02-002-00-16-001");
            }
            String orgBusinessUnitCode = result.getResult().getOrgBusinessUnitCode();
            if (StringUtil.isBlank(orgBusinessUnitCode)) {
                log.info("subTotalSalesPlanAdjustDetail月度计划{}缺少业务单位编码", batchUpdateLineStatusRequst.getPlanId());
                throw new FacadeException("OTS-02-002-00-16-002");
            }
            queryRequest.setBizId(orgBusinessUnitCode);
            queryRequest.setBizType(103);
        } else {
            switch (byOrganizationType) {
                case SALESMAN:
                    queryRequest.setManageEmployeeId(batchUpdateLineStatusRequst.getBizId());
                    break;
                case SALES_DEPARTMENT:
                    queryRequest.setOrgSalesDepartmentCode(batchUpdateLineStatusRequst.getBizId());
                    break;
                case SALES_CHANNEL:
                    queryRequest.setOrgSalesChannelCode(batchUpdateLineStatusRequst.getBizId());
                    break;
                case SALES_ORGANIZATION:
                    queryRequest.setOrgSalesOrganizationCode(batchUpdateLineStatusRequst.getBizId());
                    break;
                case BUSINESS_UNIT:
                    queryRequest.setOrgBusinessUnitCode(batchUpdateLineStatusRequst.getBizId());
                    break;
                default:
            }
        }
        queryRequest.setDir("id");
        queryRequest.setAsc(true);
        return queryRequest;
    }

    @Override
    @FacadeInvoker
    public Result<String> batchImportCreateSalesPlanAdjustDetail(List<SalesPlanAdjustDetailSDO> salesPlanAdjustDetailSDOList) {
        if (CollectionUtils.isEmpty(salesPlanAdjustDetailSDOList)) {
            throw new FacadeException("OTS-02-002-02-15-013");
        }

        SalesPlanSDO planSDO = salesPlanCommonService.checkSalesPlan(salesPlanAdjustDetailSDOList.stream().findFirst().get().getPlanId());

        //SalesPlanSDO adjustPlanSDO = salesPlanCommonService.checkSalesPlan(salesPlanAdjustDetailSDOList.stream().findFirst().get().getAdjustId().toString());

        //adjustId+客户收收获地址编码+货品编码查询重复数据，重复则更新，否则新增
        Set<Long> adjustIdSet = salesPlanAdjustDetailSDOList.stream().map(SalesPlanAdjustDetailSDO::getAdjustId).collect(Collectors.toSet());
        Set<String> customerAddresSet = salesPlanAdjustDetailSDOList.stream().map(SalesPlanAdjustDetailSDO::getCustomerAddress).collect(Collectors.toSet());
        Set<String> scItemIdSet = salesPlanAdjustDetailSDOList.stream().map(SalesPlanAdjustDetailSDO::getScItemId).collect(Collectors.toSet());
        Set<String> customerAddressIdSet = salesPlanAdjustDetailSDOList.stream().map(SalesPlanAdjustDetailSDO::getCustomerAddressId).filter(StringUtils::isNotBlank).collect(Collectors.toSet());

        SalesPlanAdjustDetailBatchQueryRequest salesPlanAdjustDetailBatchQueryRequest = new SalesPlanAdjustDetailBatchQueryRequest();
        salesPlanAdjustDetailBatchQueryRequest.setAdjustIds(Lists.newArrayList(adjustIdSet));
        salesPlanAdjustDetailBatchQueryRequest.setCustomerAddress(Lists.newArrayList(customerAddresSet));
        salesPlanAdjustDetailBatchQueryRequest.setScItemIds(Lists.newArrayList(scItemIdSet));
        if (CollectionUtils.isNotEmpty(customerAddressIdSet)) {
            salesPlanAdjustDetailBatchQueryRequest.setCustomerAddressId(Lists.newArrayList(customerAddressIdSet));
        }
        Map<String, SalesPlanAdjustDetailSDO> salesPlanAdjustMap = salesPlanAdjustDetailRepository.batchQueryDetail(salesPlanAdjustDetailBatchQueryRequest).stream()
                .collect(Collectors.toMap(x -> {
                    StringBuilder builder = new StringBuilder(x.getAdjustId().toString());
                    if (StringUtils.isNotBlank(x.getCustomerAddressId())) {
                        builder.append(x.getCustomerAddressId());
                    }
                    builder.append(x.getCustomerAddress()).append(x.getScItemId());
                    return builder.toString();
                }, a -> a, (a, b) -> a));

        //新增
        List<SalesPlanAdjustDetailSDO> batchCreateRequestList = new ArrayList<>();
        //修改
        List<SalesPlanAdjustDetailSDO> batchEditRequestList = new ArrayList<>();
        for (SalesPlanAdjustDetailSDO adjustDetailSDO : salesPlanAdjustDetailSDOList) {
            StringBuilder builder = new StringBuilder(adjustDetailSDO.getAdjustId().toString());
            if (StringUtils.isNotBlank(adjustDetailSDO.getCustomerAddressId())) {
                builder.append(adjustDetailSDO.getCustomerAddressId());
            }
            builder.append(adjustDetailSDO.getCustomerAddress()).append(adjustDetailSDO.getScItemId());
            String key = builder.toString();
            SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = salesPlanAdjustMap.get(key);
            if (Objects.isNull(salesPlanAdjustDetailSDO)) {
                batchCreateRequestList.add(adjustDetailSDO);
            } else {
                Integer adjustCount = Optional.ofNullable(adjustDetailSDO.getAdjustCount()).orElse(0);
                Integer monthFirstAdjustCount = Optional.ofNullable(adjustDetailSDO.getMonthFirstAdjustCount()).orElse(0);
                Integer monthMiddleAdjustCount = Optional.ofNullable(adjustDetailSDO.getMonthMiddleAdjustCount()).orElse(0);
                Integer monthLastAdjustCount = Optional.ofNullable(adjustDetailSDO.getMonthLastAdjustCount()).orElse(0);
                Integer monthFirstAdjustReturnCount = Optional.ofNullable(adjustDetailSDO.getMonthFirstAdjustReturnCount()).orElse(0);
                Integer monthMiddleAdjustReturnCount = Optional.ofNullable(adjustDetailSDO.getMonthMiddleAdjustReturnCount()).orElse(0);
                Integer monthLastAdjustReturnCount = Optional.ofNullable(adjustDetailSDO.getMonthLastAdjustReturnCount()).orElse(0);
                BeanUtils.copyProperties(salesPlanAdjustDetailSDO, adjustDetailSDO);
                adjustDetailSDO.setAdjustCount(adjustCount);
                adjustDetailSDO.setMonthFirstAdjustCount(monthFirstAdjustCount);
                adjustDetailSDO.setMonthMiddleAdjustCount(monthMiddleAdjustCount);
                adjustDetailSDO.setMonthLastAdjustCount(monthLastAdjustCount);
                adjustDetailSDO.setMonthFirstAdjustReturnCount(monthFirstAdjustReturnCount);
                adjustDetailSDO.setMonthMiddleAdjustReturnCount(monthMiddleAdjustReturnCount);
                adjustDetailSDO.setMonthLastAdjustReturnCount(monthLastAdjustReturnCount);
                batchEditRequestList.add(adjustDetailSDO);
            }
        }
        Integer count = 0;
        if (batchCreateRequestList.size() > 0) {
            //添加月度计划明细
            List<SalesPlanLineSDO> salesPlanLineSDOList = batchCreateRequestList.stream().map(salesPlanAdjustDetailSDO -> {
                SalesPlanLineSDO salesPlanLineSDO = SalesPlanLineSDO.builder().build();
                BeanUtils.copyProperties(salesPlanAdjustDetailSDO, salesPlanLineSDO);
                salesPlanLineSDO.setStatus(SalesPlanLineStatusEnum.ADJUST_ADD.getStatus());
                return salesPlanLineSDO;
            }).collect(Collectors.toList());

            //补上计划明细的客户组
            Set<String> customerCodeSet = salesPlanLineSDOList.stream().map(SalesPlanLineSDO::getCustomerCode).collect(Collectors.toSet());
            Map<String, CustomerSaleScope> customerSaleScopeMap = salesPlanOutCommonService.getCustomerSaleScopeMap(customerCodeSet);
            for (SalesPlanLineSDO planLineSDO : salesPlanLineSDOList) {
                CustomerSaleScope customerSaleScope = customerSaleScopeMap.get(planLineSDO.getCustomerCode());
                if (customerSaleScope!=null) {
                    planLineSDO.setParam2(customerSaleScope.getCustomerGroup());
                }
            }

            //补充业中计划明细字段
            enichBcPlanField(salesPlanLineSDOList,planSDO);

            String successCount = salesPlanLineAbility.batchCreateSalesPlanLine(salesPlanLineSDOList);
            if (Integer.valueOf(successCount) > 0) {
                //新增调整明细
                SalesPlanAdjustDetailSDO firstPlanAdjustDetailSDO = salesPlanAdjustDetailSDOList.stream().findFirst().get();
                PageQueryPlanLineRequest queryPlanLineRequest = new PageQueryPlanLineRequest();
                queryPlanLineRequest.setPlanId(firstPlanAdjustDetailSDO.getPlanId());
                queryPlanLineRequest.setStatus(SalesPlanLineStatusEnum.ADJUST_ADD.getStatus());
                queryPlanLineRequest.setCustomerAddresss(Lists.newArrayList(customerAddresSet));
                if (CollectionUtils.isNotEmpty(customerAddressIdSet)) {
                    queryPlanLineRequest.setCustomerAddressIdList(Lists.newArrayList(customerAddressIdSet));
                }
                queryPlanLineRequest.setScItemIds(Lists.newArrayList(scItemIdSet));
                //获取总数
                PageResult<List<SalesPlanLineSDO>> listPageResult = salesPlanLineRepository.pageQuerySalesPlanLineAdjustAddList(queryPlanLineRequest);
                int totalPage = (listPageResult.getTotal() + SALES_PLAN_LIN_PAGE_SIZE - 1) / SALES_PLAN_LIN_PAGE_SIZE;
                //调整明细数据
                List<SalesPlanAdjustDetailSDO> sdoList = new ArrayList<>();
                for (int i = 1; i <= totalPage; i++) {
                    String adjustId = batchCreateRequestList.stream().findFirst().get().getAdjustId().toString();
                    SalesPlanSDO salesPlanSDO = salesPlanCommonService.checkSalesPlan(adjustId);
                    queryPlanLineRequest.setSize(SALES_PLAN_LIN_PAGE_SIZE);
                    queryPlanLineRequest.setPage(i);
                    PageResult<List<SalesPlanLineSDO>> listPageResult2 = salesPlanLineRepository.pageQuerySalesPlanLineAdjustAddList(queryPlanLineRequest);
                    if (CollectionUtils.isEmpty(listPageResult2.getContent())) {
                        break;
                    }
                    listPageResult2.getContent().forEach(salesPlanLineSDO -> {
                        SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = SalesPlanAdjustDetailSDO.builder().build();
                        BeanUtils.copyProperties(salesPlanLineSDO, salesPlanAdjustDetailSDO);
                        salesPlanAdjustDetailSDO.setAdjustId(firstPlanAdjustDetailSDO.getAdjustId());
                        salesPlanAdjustDetailSDO.setPlanId(firstPlanAdjustDetailSDO.getPlanId());
                        salesPlanAdjustDetailSDO.setPlanDetailId(salesPlanLineSDO.getId());
                        salesPlanAdjustDetailSDO.setEstimatedDiscountRate(salesPlanLineSDO.getEstimatedDiscountRate().longValue());
                        salesPlanAdjustDetailSDO.setStatus(SalesPlanLineStatusEnum.FINISH.getStatus());
                        //调整新数据标识
                        SalesPlanAdjustDetailFeatures salesPlanAdjustDetailFeatures = new SalesPlanAdjustDetailFeatures();
                        salesPlanAdjustDetailFeatures.setIsHistory(false);
                        salesPlanAdjustDetailSDO.setFeatures(JSONObject.toJSONString(salesPlanAdjustDetailFeatures));
                        Long costInsuranceFreight = Optional.ofNullable(salesPlanAdjustDetailSDO.getCostInsuranceFreight()).orElse(0L);
                        BigDecimal estimateDiscount = Optional.ofNullable(salesPlanSDO.getEstimateDiscount()).orElse(new BigDecimal(0));

                        //调整提报量
                        Integer monthAdjustCount = Optional.ofNullable(salesPlanLineSDO.getMonthFirstAdjustCount()).orElse(0) + Optional.ofNullable(salesPlanLineSDO.getMonthMiddleAdjustCount()).orElse(0) + Optional.ofNullable(salesPlanLineSDO.getMonthLastAdjustCount()).orElse(0);
                        //计算折前折后满足度
                        salesPlanAdjustDetailSDO.calculateMonthSatisfaction(costInsuranceFreight, estimateDiscount);
                        //计算折前折后任务金额
                        salesPlanAdjustDetailSDO.calculateMonthMoney(costInsuranceFreight, estimateDiscount);
                        //调整提报到岸金额=调整提报数量*到岸价
                        long outboundPrice = Objects.nonNull(salesPlanLineSDO.getOutboundPrice()) ? salesPlanLineSDO.getOutboundPrice() : 0;
                        long beforeMonthOutboundMoney = monthAdjustCount * outboundPrice;
                        salesPlanAdjustDetailSDO.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
                        //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
                        salesPlanAdjustDetailSDO.calculateMonthOutboundMoney(salesPlanSDO.getEstimateDiscount());
                        sdoList.add(salesPlanAdjustDetailSDO);

                        /*//调整回复量
                        Integer monthAdjustReturnCount = Optional.ofNullable(salesPlanLineSDO.getMonthFirstAdjustReturnCount()).orElse(0) + Optional.ofNullable(salesPlanLineSDO.getMonthMiddleAdjustReturnCount()).orElse(0) + Optional.ofNullable(salesPlanLineSDO.getMonthLastAdjustReturnCount()).orElse(0);
                        //回复量不为空时,计算按照发布后公式计算
                        if (0 != monthAdjustReturnCount || 0 != salesPlanLineSDO.getMonthFirstAdjustReturnCount() ||
                                0 != salesPlanLineSDO.getMonthMiddleAdjustReturnCount() || 0 != salesPlanLineSDO.getMonthLastAdjustReturnCount()) {
                            //计算折前折后满足度
                            salesPlanAdjustDetailSDO.calculateTaskReturnSatisfaction(costInsuranceFreight, estimateDiscount);
                            //计算折前折后任务金额
                            salesPlanAdjustDetailSDO.calculateTaskReturnMoney(costInsuranceFreight, estimateDiscount);
                            //到岸折前金额=（任务数量+调整回复数量）*到岸价
                            long outboundPrice = Objects.nonNull(salesPlanLineSDO.getOutboundPrice()) ? salesPlanLineSDO.getOutboundPrice() : 0;
                            long beforeMonthOutboundMoney = (salesPlanLineSDO.getTaskCount() + monthAdjustReturnCount) * outboundPrice;
                            salesPlanAdjustDetailSDO.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
                            //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
                            salesPlanAdjustDetailSDO.calculateMonthOutboundMoney(salesPlanSDO.getEstimateDiscount());
                            sdoList.add(salesPlanAdjustDetailSDO);
                        } else if (0 != monthAdjustCount || 0 != salesPlanLineSDO.getMonthFirstAdjustCount() ||
                                0 != salesPlanLineSDO.getMonthMiddleAdjustCount() || 0 != salesPlanLineSDO.getMonthLastAdjustCount()) {
                            //提报量不为空时,计算按照调整待发布状态公式计算
                            //计算折前折后满足度
                            salesPlanAdjustDetailSDO.calculateMonthSatisfaction(costInsuranceFreight, estimateDiscount);
                            //计算折前折后任务金额
                            salesPlanAdjustDetailSDO.calculateMonthMoney(costInsuranceFreight, estimateDiscount);
                            //调整提报到岸金额=调整提报数量*到岸价
                            long outboundPrice = Objects.nonNull(salesPlanLineSDO.getOutboundPrice()) ? salesPlanLineSDO.getOutboundPrice() : 0;
                            long beforeMonthOutboundMoney = monthAdjustCount * outboundPrice;
                            salesPlanAdjustDetailSDO.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
                            //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
                            salesPlanAdjustDetailSDO.calculateMonthOutboundMoney(salesPlanSDO.getEstimateDiscount());
                            sdoList.add(salesPlanAdjustDetailSDO);
                        }*/
                    });
                }

                String s = salesPlanAdjustDetailAbility.batchCreateSalesPlanAdjustDetail(sdoList);
                count += Integer.valueOf(s);
            }
        }
        if (batchEditRequestList.size() > 0) {
            for (SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO : batchEditRequestList) {
                EditSalesPlanAdjustDetailRequest editSalesPlanAdjustDetailRequest = new EditSalesPlanAdjustDetailRequest();
                editSalesPlanAdjustDetailRequest.setId(salesPlanAdjustDetailSDO.getId().toString());
                editSalesPlanAdjustDetailRequest.setMonthFirstAdjustCount(salesPlanAdjustDetailSDO.getMonthFirstAdjustCount());
                editSalesPlanAdjustDetailRequest.setMonthMiddleAdjustCount(salesPlanAdjustDetailSDO.getMonthMiddleAdjustCount());
                editSalesPlanAdjustDetailRequest.setMonthLastAdjustCount(salesPlanAdjustDetailSDO.getMonthLastAdjustCount());
//                editSalesPlanAdjustDetailRequest.setMonthFirstAdjustReturnCount(salesPlanAdjustDetailSDO.getMonthFirstAdjustReturnCount());
//                editSalesPlanAdjustDetailRequest.setMonthMiddleAdjustReturnCount(salesPlanAdjustDetailSDO.getMonthMiddleAdjustReturnCount());
//                editSalesPlanAdjustDetailRequest.setMonthLastAdjustReturnCount(salesPlanAdjustDetailSDO.getMonthLastAdjustReturnCount());
                editSalesPlanAdjustDetail(editSalesPlanAdjustDetailRequest);
            }
        }
        return Result.success(count.toString());
    }

    private SalesPlanAdjustDetailSDO editSalesPlanRequestConverter(SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO, EditSalesPlanAdjustDetailRequest editSalesPlanAdjustDetailRequest) {
        // 构建失焦保存的sdo
        SalesPlanAdjustDetailSDO editSdo = SalesPlanAdjustDetailSDO.builder().build();
        BeanUtils.copyProperties(salesPlanAdjustDetailSDO, editSdo);

        Long adjustId = salesPlanAdjustDetailSDO.getAdjustId();
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        querySalesPlanRequest.setId(adjustId.toString());
        Result<SalesPlanSDO> salesPlan = salesPlanQueryService.getSalesPlan(querySalesPlanRequest);
        SalesPlanSDO salesPlanSDO = salesPlan.getResult();
        if (Objects.isNull(salesPlanSDO)) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        //根据调整计划设置修改上中下旬的值
        if (Optional.ofNullable(salesPlanSDO.getMonthFirst()).orElse(true)) {
            //调整量
            if (null != Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthFirstAdjustCount()).orElse(0)) {
                if (Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthFirstAdjustCount()).orElse(0) + editSdo.getMonthFirstTaskCount() < 0) {
                    throw new FacadeException("OTS-02-005-00-15-029");
                }
                //上旬调整量
                editSdo.setMonthFirstAdjustCount(Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthFirstAdjustCount()).orElse(0));
            }
        }
        if (Optional.ofNullable(salesPlanSDO.getMonthMiddle()).orElse(true)) {
            if (null != Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustCount()).orElse(0)) {
                if (Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustCount()).orElse(0) + editSdo.getMonthMiddleTaskCount() < 0) {
                    throw new FacadeException("OTS-02-005-00-15-030");
                }
                //中旬调整量
                editSdo.setMonthMiddleAdjustCount(Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustCount()).orElse(0));
            }
        }
        if (Optional.ofNullable(salesPlanSDO.getMonthLast()).orElse(true)) {
            if (null != Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthLastAdjustCount()).orElse(0)) {
                if (Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthLastAdjustCount()).orElse(0) + editSdo.getMonthLastTaskCount() < 0) {
                    throw new FacadeException("OTS-02-005-00-15-031");
                }
                //下旬调整量
                editSdo.setMonthLastAdjustCount(Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthLastAdjustCount()).orElse(0));
            }
        }
        //发布前计算逻辑
        //调整量
        Integer adjustCount = Optional.ofNullable(editSdo.getMonthFirstAdjustCount()).orElse(0) + Optional.ofNullable(editSdo.getMonthMiddleAdjustCount()).orElse(0) + Optional.ofNullable(editSdo.getMonthLastAdjustCount()).orElse(0);
        editSdo.setAdjustCount(adjustCount);
        //折前调整金额
        long costInsuranceFreight = Objects.nonNull(editSdo.getCostInsuranceFreight()) ? editSdo.getCostInsuranceFreight() : 0;
        long beforeAdjustMoney = editSdo.getAdjustCount() * costInsuranceFreight;
        editSdo.setBeforeAdjustMoney(beforeAdjustMoney);

        //计算折后调整金额  折后调整金额=折前调整金额*(1-预估价格折扣率)
        editSdo.calculateAdjustMoney(salesPlanSDO.getEstimateDiscount());
        editSdo.calculateAdjustSatisfaction();
        //到岸折前金额
        long outboundPrice = Objects.nonNull(salesPlanAdjustDetailSDO.getOutboundPrice()) ? salesPlanAdjustDetailSDO.getOutboundPrice() : 0;
        long beforeMonthOutboundMoney = editSdo.getAdjustCount() * outboundPrice;
        editSdo.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
        //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
        editSdo.calculateMonthOutboundMoney(salesPlanSDO.getEstimateDiscount());
        //折前满足度=（任务量+调整提报量）*货品常规价
        Integer taskCount = Objects.isNull(editSdo.getTaskCount()) ? 0 : editSdo.getTaskCount();
        Integer taskAdjustCount = taskCount + editSdo.getAdjustCount();
        //折前任务金额=（任务量+调整提报量）*货品常规价
        Long costInsuranceFreight1 = Objects.nonNull(editSdo.getCostInsuranceFreight()) ? editSdo.getCostInsuranceFreight() : 0;
        Long beforeTaskMoney = taskCount * costInsuranceFreight1;
        //落库的折前任务金额（任务量*单价）
        editSdo.setBeforeTaskMoney(beforeTaskMoney);
        //不落库的任务金额（任务量+调整提报量）*货品常规价 用来计算满足度
        long notBeforeTaskMoney = taskAdjustCount * costInsuranceFreight1;
        //折前满足度=(折前任务金额/折前合同金额)
        BigDecimal beforeContractSatisfaction = CalculatePercentage.retainTwo(notBeforeTaskMoney, editSdo.getBeforeMonthContractMoney());
        editSdo.setBeforeContractSatisfaction(beforeContractSatisfaction);
        //折后任务金额=（任务量+调整提报量）*货品常规价*（1-预估价格折扣率）
        editSdo.calculateTaskMoney(salesPlanSDO.getEstimateDiscount());
        //折后满足度=(折后任务金额/折后合同金额)
        BigDecimal contractSatisfaction = CalculatePercentage.retainTwoBigDecimal(new BigDecimal(editSdo.getTaskMoney()), new BigDecimal(editSdo.getMonthContractMoney()));
        editSdo.setContractSatisfaction(contractSatisfaction);
        editSdo.setGmtModified(new Date());
        return editSdo;
    }

/*    private SalesPlanAdjustDetailSDO editSalesPlanRequestConverter(SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO, EditSalesPlanAdjustDetailRequest editSalesPlanAdjustDetailRequest) {
        // 构建失焦保存的sdo
        SalesPlanAdjustDetailSDO editSdo = SalesPlanAdjustDetailSDO.builder().build();
        BeanUtils.copyProperties(salesPlanAdjustDetailSDO, editSdo);

        Long adjustId = salesPlanAdjustDetailSDO.getAdjustId();
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        querySalesPlanRequest.setId(adjustId.toString());
        Result<SalesPlanSDO> salesPlan = salesPlanQueryService.getSalesPlan(querySalesPlanRequest);
        SalesPlanSDO salesPlanSDO = salesPlan.getResult();
        if (Objects.isNull(salesPlanSDO)) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        //调整量
        Integer adjustCount = Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthFirstAdjustCount()).orElse(0) + Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustCount()).orElse(0) + Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthLastAdjustCount()).orElse(0);
        Integer monthAdjustReturnCount = Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthFirstAdjustReturnCount()).orElse(0) + Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustReturnCount()).orElse(0) + Optional.ofNullable(editSalesPlanAdjustDetailRequest.getMonthLastAdjustReturnCount()).orElse(0);
        if (0 != adjustCount || 0 != editSalesPlanAdjustDetailRequest.getMonthFirstAdjustCount() ||
                0 != editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustCount() ||
                0 != editSalesPlanAdjustDetailRequest.getMonthLastAdjustCount()) {
            //根据调整计划设置修改上中下旬的值
            if (Optional.ofNullable(salesPlanSDO.getMonthFirst()).orElse(true)) {
                //调整量
                if (editSalesPlanAdjustDetailRequest.getMonthFirstAdjustCount() != null) {
                    if (editSalesPlanAdjustDetailRequest.getMonthFirstAdjustCount() + editSdo.getMonthFirstTaskCount() < 0) {
                        throw new FacadeException("OTS-02-005-00-15-002");
                    }
                    //上旬调整量
                    editSdo.setMonthFirstAdjustCount(editSalesPlanAdjustDetailRequest.getMonthFirstAdjustCount());
                }
            }
            if (Optional.ofNullable(salesPlanSDO.getMonthMiddle()).orElse(true)) {
                if (editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustCount() != null) {
                    if (editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustCount() + editSdo.getMonthMiddleTaskCount() < 0) {
                        throw new FacadeException("OTS-02-005-00-15-002");
                    }
                    //中旬调整量
                    editSdo.setMonthMiddleAdjustCount(editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustCount());
                }
            }
            if (Optional.ofNullable(salesPlanSDO.getMonthLast()).orElse(true)) {
                if (editSalesPlanAdjustDetailRequest.getMonthLastAdjustCount() != null) {
                    if (editSalesPlanAdjustDetailRequest.getMonthLastAdjustCount() + editSdo.getMonthLastTaskCount() < 0) {
                        throw new FacadeException("OTS-02-005-00-15-002");
                    }
                    //下旬调整量
                    editSdo.setMonthLastAdjustCount(editSalesPlanAdjustDetailRequest.getMonthLastAdjustCount());
                }
            }
            //发布前计算逻辑
            //调整量
            Integer adjustCount2 = Optional.ofNullable(editSdo.getMonthFirstAdjustCount()).orElse(0) + Optional.ofNullable(editSdo.getMonthMiddleAdjustCount()).orElse(0) + Optional.ofNullable(editSdo.getMonthLastAdjustCount()).orElse(0);
            editSdo.setAdjustCount(adjustCount2);
            //折前调整金额
            long costInsuranceFreight = Objects.nonNull(editSdo.getCostInsuranceFreight()) ? editSdo.getCostInsuranceFreight() : 0;
            long beforeAdjustMoney = editSdo.getAdjustCount() * costInsuranceFreight;
            editSdo.setBeforeAdjustMoney(beforeAdjustMoney);

            //计算折后调整金额  折后调整金额=折前调整金额*(1-预估价格折扣率)
            editSdo.calculateAdjustMoney(salesPlanSDO.getEstimateDiscount());
            editSdo.calculateAdjustSatisfaction();
            //到岸折前金额
            long outboundPrice = Objects.nonNull(salesPlanAdjustDetailSDO.getOutboundPrice()) ? salesPlanAdjustDetailSDO.getOutboundPrice() : 0;
            long beforeMonthOutboundMoney = adjustCount * outboundPrice;
            editSdo.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
            //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
            editSdo.calculateMonthOutboundMoney(salesPlanSDO.getEstimateDiscount());
            //折前满足度=（任务量+调整提报量）*货品常规价
            Integer taskCount = Objects.isNull(editSdo.getTaskCount()) ? 0 : editSdo.getTaskCount();
            Integer taskAdjustCount = taskCount + editSdo.getAdjustCount();
            //折前任务金额=（任务量+调整提报量）*货品常规价
            Long beforeTaskMoney = taskCount * editSdo.getCostInsuranceFreight();
            //落库的折前任务金额（任务量*单价）
            editSdo.setBeforeTaskMoney(beforeTaskMoney);
            //不落库的任务金额（任务量+调整提报量）*货品常规价 用来计算满足度
            long notBeforeTaskMoney = taskAdjustCount * editSdo.getCostInsuranceFreight();
            //折前满足度=(折前任务金额/折前合同金额)
            BigDecimal beforeContractSatisfaction = CalculatePercentage.retainTwo(notBeforeTaskMoney, editSdo.getBeforeMonthContractMoney());
            editSdo.setBeforeContractSatisfaction(beforeContractSatisfaction);
            //折后任务金额=（任务量+调整提报量）*货品常规价*（1-预估价格折扣率）
            editSdo.calculateTaskMoney(salesPlanSDO.getEstimateDiscount());
            //折后满足度=(折后任务金额/折后合同金额)
            BigDecimal contractSatisfaction = CalculatePercentage.retainTwoBigDecimal(new BigDecimal(editSdo.getTaskMoney()), new BigDecimal(editSdo.getMonthContractMoney()));
            editSdo.setContractSatisfaction(contractSatisfaction);
        } else if (0 != monthAdjustReturnCount || 0 != editSalesPlanAdjustDetailRequest.getMonthFirstAdjustReturnCount() ||
                0 != editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustReturnCount() ||
                0 != editSalesPlanAdjustDetailRequest.getMonthLastAdjustReturnCount()) {
            //根据调整计划设置修改上中下旬的值
            if (Optional.ofNullable(salesPlanSDO.getMonthFirst()).orElse(true)) {
                //上旬调整回复量
                if (null != editSalesPlanAdjustDetailRequest.getMonthFirstAdjustReturnCount()) {
                    editSdo.setMonthFirstAdjustReturnCount(editSalesPlanAdjustDetailRequest.getMonthFirstAdjustReturnCount());
                }
            }
            if (Optional.ofNullable(salesPlanSDO.getMonthMiddle()).orElse(true)) {
                //中旬调整回复量
                if (null != editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustReturnCount()) {
                    editSdo.setMonthMiddleAdjustReturnCount(editSalesPlanAdjustDetailRequest.getMonthMiddleAdjustReturnCount());
                }
            }
            if (Optional.ofNullable(salesPlanSDO.getMonthMiddle()).orElse(true)) {
                //下旬调整回复量
                if (null != editSalesPlanAdjustDetailRequest.getMonthLastAdjustReturnCount()) {
                    editSdo.setMonthLastAdjustReturnCount(editSalesPlanAdjustDetailRequest.getMonthLastAdjustReturnCount());
                }
            }
            //按照发布后的计算逻辑
            Long costInsuranceFreight = Optional.ofNullable(editSdo.getCostInsuranceFreight()).orElse(0L);
            BigDecimal estimateDiscount = Optional.ofNullable(salesPlanSDO.getEstimateDiscount()).orElse(new BigDecimal(0));
            //发布后计算逻辑
            //计算折前折后满足度
            editSdo.calculateTaskReturnSatisfaction(costInsuranceFreight, estimateDiscount);
            //计算折前折后任务金额
            editSdo.calculateTaskReturnMoney(costInsuranceFreight, estimateDiscount);
            //到岸折前金额=（任务数量+调整回复数量）*到岸价
            long outboundPrice = Objects.nonNull(editSdo.getOutboundPrice()) ? editSdo.getOutboundPrice() : 0;
            long beforeMonthOutboundMoney = (editSdo.getTaskCount() + monthAdjustReturnCount) * outboundPrice;
            editSdo.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
            //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
            editSdo.calculateMonthOutboundMoney(salesPlanSDO.getEstimateDiscount());
        }
        editSdo.setGmtModified(new Date());
        return editSdo;
    }*/
}
